package com.ming_za.sokoban.network;

import com.ming_za.sokoban.block.BoxBlock;
import com.ming_za.sokoban.block.EndBlock;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.network.NetworkEvent;

import java.util.Objects;
import java.util.function.Supplier;

public class UpdateClient {

    /**
     * 数据类型：
     *  type = 0;方块位置数据
     *  type = 1;粒子效果数据
     */
    private final int type;

    private final BlockPos pos;
    private final BlockPos rPos;

    public UpdateClient(int type, BlockPos pos, BlockPos rPos) {
        this.type = type;
        this.pos = pos;
        this.rPos = rPos;
    }

    //打包
    public static void encode(UpdateClient message, FriendlyByteBuf buf){
        buf.writeVarInt(message.type).writeBlockPos(message.pos).writeBlockPos(message.rPos);
    }

    //解包
    public static UpdateClient decode(FriendlyByteBuf buf){
        return new UpdateClient(buf.readVarInt(),buf.readBlockPos(),buf.readBlockPos());
    }

    //监听
    public static void handle(UpdateClient message, Supplier<NetworkEvent.Context> contextSupplier){
        NetworkEvent.Context context = contextSupplier.get();
        if (context.getDirection().getOriginationSide() == LogicalSide.SERVER){

            Minecraft minecraft = Minecraft.getInstance();
            minecraft.submitAsync(()-> {

                if (message.type == 0){
                    //更新方块数据
                    if (Objects.requireNonNull(minecraft.player).level.getBlockState(message.rPos).getBlock() instanceof BoxBlock boxBlock){
                        boxBlock.updateBlock(message.pos,message.rPos);
                    }
                }else if (message.type == 1){
                    //更新粒子数据
                    if (Objects.requireNonNull(minecraft.player).level.getBlockState(message.rPos).getBlock() instanceof EndBlock endBlock){
                        endBlock.addParticle(message.pos);

                        ClientLevel level = Minecraft.getInstance().level;
                        assert level != null;
                        level.setBlock(message.pos,level.getBlockState(message.pos).setValue(BoxBlock.HOMING,true),3);

                    }
                }
            });
            context.setPacketHandled(true);
        }
    }
}
